<template>
  <div>
    <el-row>
      <el-col :span="12">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" style="width: 300px" :disabled="dialogType===0" placeholder="请输入" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="比对模板" prop="contrastTemplatePkId">
          <el-select
            v-model="form.contrastTemplatePkId"
            filterable
            :disabled="dialogType===0"
            placeholder="请选择"
            clearable
            style="width:300px"
          >
            <el-option v-for="item in contrastTemplate" :key="item.pkId" :label="item.name" :value="item.pkId" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="迁移类型" prop="migrationType">
          <el-select v-model="form.migrationType" :disabled="form.isHiddenValu" placeholder="请选择迁移类型" clearable filterable @change="changeMigrationType">
            <el-option
              v-for="item in migrationTypeList"
              :key="item.name"
              :label="item.name"
              :value="item.name"
              :disabled="!item.enabled"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="数据服务器" prop="serverPkId">
          <el-select
            v-model="form.serverPkId"
            filterable
            :disabled="dialogType===0"
            placeholder="请选择"
            clearable
            style="width:300px"
            @change="getDatabaseByDataSource()"
          >
            <el-option v-for="item in sourceConnList" :key="item.pkId" :label="item.sourceName" :value="item.pkId" />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <!-- <el-col :span="12">
        <el-form-item label="导入方式">
          <el-radio-group
            v-model="createTaskType"
            :disabled="dialogType===0"
            style="float: left;margin-right: 40px"
          >
            <el-radio-button style="float: left" label="直连" />
            <el-radio-button label="导入" />
          </el-radio-group>
        </el-form-item>
      </el-col> -->
      <el-col v-if="createTaskType==='直连'" :span="12">
        <el-form-item label="库名" prop="sourceDbName">
          <el-select
            v-model="form.sourceDbName"
            filterable
            :disabled="dialogType===0"
            placeholder="请选择"
            clearable
            style="width:200px"
          >
            <el-option v-for="item in dataDbList" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-button :disabled="chooseTableDisable()" type="text" @click="toAddTaskList">选择需要比对的表</el-button>
      </el-col>
      <el-col v-if="createTaskType==='导入'" :span="12">
        <el-form-item label="操作">
          <el-button
            style="float: left;margin-right: 5px"
            size="mini"
            :loading="downloadLoading"
            type="primary"
            icon="el-icon-download"
            @click="templateDownload"
          >
            模板下载
          </el-button>
          <el-upload
            ref="uploadExcel"
            style="display: inline-block"
            class="upload-demo"
            :loading="uploadLoading"
            action=""
            multiple
            :auto-upload="false"
            :on-change="handleUploadJobChange"
            :file-list="fileList"
            :show-file-list="false"
          >
            <div>
              <el-button
                style="float: left;"
                size="mini"
                type="primary"
                icon="el-icon-upload2"
              >
                文件上传
              </el-button>
            </div>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
    <div>
      <el-form ref="form" :inline="true" label-width="130px" style="float: left;margin: 5px 0 0 20px">
        <el-form-item label="">
          <el-input v-model="query.sourceTableName" style="width: 300px" placeholder="源表" clearable @keyup.native.enter="crud.toQuery" />
        </el-form-item>
      </el-form>
    </div>
    <div>
      <crudOperation style="float: left" />
      <el-button
        v-if="crud.optShow.del"
        slot="reference"
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        size="mini"
        style="margin: 6px 0 0 10px"
        :loading="crud.delAllLoading"
        :disabled="crud.selections.length === 0 || dialogType===0"
        @click="toDelete(crud.selections)"
      >
        删除
      </el-button>
    </div>
    <el-table
      ref="table"
      border
      :data="form.dataContrastList"
      max-height="280"
      @selection-change="crud.selectionChangeHandler"
      @filter-change="crud.handleFilterChange"
    >
      <el-table-column fixed type="selection" width="55" />
      <el-table-column fixed prop="sourceDbName" label="源库" width="120" />
      <el-table-column fixed prop="sourceTableName" label="源表" width="140" />
      <el-table-column fixed prop="contrastDbName" label="目标库" width="120" />
      <el-table-column fixed prop="contrastTableName" label="目标表" width="140" />
      <el-table-column prop="whereCondition" label="where条件">
        <template slot-scope="scope">
          <el-button
            :disabled="dialogType===0"
            type="text"
            size="mini"
            @click="whereConditionEdit(scope.row.whereCondition, scope.$index)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="sortField" label="排序字段">
        <template slot-scope="scope">
          <el-button
            :disabled="dialogType===0"
            type="text"
            size="mini"
            @click="sortFieldEdit(scope.row.sortField, scope.$index)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="removeRepeatCountField" label="去重count" width="110">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.removeRepeatCountField"
            filterable
            multiple
            :disabled="dialogType===0"
            placeholder="请选择"
            clearable
          >
            <el-option v-for="val in scope.row.tableFieldsList" :key="val" :label="val" :value="val" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="groupCountField" label="分组count" width="110">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.groupCountField"
            filterable
            multiple
            :disabled="dialogType===0"
            placeholder="请选择"
            clearable
          >
            <el-option v-for="val in scope.row.tableFieldsList" :key="val" :label="val" :value="val" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="countField" label="字段count" width="110">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.countField"
            filterable
            multiple
            :disabled="dialogType===0"
            placeholder="请选择"
            clearable
          >
            <el-option v-for="val in scope.row.tableFieldsList" :key="val" :label="val" :value="val" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="excludeField" label="排除字段" width="110">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.excludeField"
            filterable
            multiple
            :disabled="dialogType===0"
            placeholder="请选择"
            clearable
          >
            <el-option v-for="val in scope.row.tableFieldsList" :key="val" :label="val" :value="val" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="sumField" label="字段sum" width="110">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.sumField"
            filterable
            multiple
            :disabled="dialogType===0"
            placeholder="请选择"
            clearable
          >
            <el-option v-for="val in scope.row.tableFieldsList" :key="val" :label="val" :value="val" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="trimField" label="字段trim" width="110">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.trimField"
            filterable
            multiple
            :disabled="dialogType===0"
            placeholder="请选择"
            clearable
          >
            <el-option v-for="val in scope.row.tableFieldsList" :key="val" :label="val" :value="val" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="emptyField" label="空值count" width="110">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.emptyField"
            filterable
            multiple
            :disabled="dialogType===0"
            placeholder="请选择"
            clearable
          >
            <el-option v-for="val in scope.row.tableFieldsList" :key="val" :label="val" :value="val" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="customSql" label="自定义sql">
        <template slot-scope="scope">
          <el-button
            :disabled="dialogType===0"
            type="text"
            size="mini"
            @click="customSqlEdit(scope.row.customSql, scope.$index)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="contrastScene" label="比对场景" width="120">
        <template slot-scope="scope">
          <el-select v-model="scope.row.contrastScene" filterable :disabled="dialogType===0" placeholder="请选择" clearable>
            <el-option v-for="item in contrastSceneOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </template>
      </el-table-column>
    </el-table>
    <pagination />
    <!-- where条件 填写弹窗 -->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="whereConditionClose"
      :visible.sync="whereConditionFlag"
      title="where条件"
      width="800px"
    >
      <el-form-item label="源where条件">
        <el-input v-model="sourceWhereCondition" type="textarea" :rows="5" placeholder="请输入来源数据的where条件，如field1='A' AND field2='B'" style="width: 540px;" />
      </el-form-item>
      <el-form-item label="目标where条件">
        <el-input v-model="targetWhereCondition" type="textarea" :rows="5" placeholder="请输入目标数据的where条件，如field1='A' AND field2='B'" style="width: 540px;" />
      </el-form-item>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="whereConditionFlag=false">取消</el-button>
        <el-button type="primary" @click="whereConditionSubmit()">保存</el-button>
      </div>
    </el-dialog>
    <!-- 排序字段 填写弹窗 -->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="sortFieldClose"
      :visible.sync="sortFieldFlag"
      title="排序字段"
      width="800px"
    >
      <el-form-item label="源排序字段">
        <el-input v-model="sourceSortField" type="textarea" :rows="5" placeholder="请输入来源数据的排序字段规则，逗号分隔，如field1, field2, field3" style="width: 540px;" />
      </el-form-item>
      <el-form-item label="目标排序字段">
        <el-input v-model="targetSortField" type="textarea" :rows="5" placeholder="请输入目标数据的排序字段规则，逗号分隔，如field1, field2, field3" style="width: 540px;" />
      </el-form-item>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="sortFieldFlag=false">取消</el-button>
        <el-button type="primary" @click="sortFieldSubmit()">保存</el-button>
      </div>
    </el-dialog>
    <!-- 自定义SQL填写弹窗 -->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="sqlClose"
      :visible.sync="customSqlFlag"
      title="sql语句"
      width="800px"
    >
      <el-form-item label="源sql语句">
        <el-input v-model="sourceCustomSql" type="textarea" :rows="5" placeholder="请输入" style="width: 540px;" />
      </el-form-item>
      <el-form-item label="目标sql语句">
        <el-input v-model="targetCustomSql" type="textarea" :rows="5" placeholder="请输入" style="width: 540px;" />
      </el-form-item>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="customSqlFlag=false">取消</el-button>
        <el-button type="primary" @click="sqlSubmit()">保存</el-button>
      </div>
    </el-dialog>
    <!--对比清单选择-->
    <el-dialog
      :visible.sync="chooseTable"
      :modal-append-to-body="false"
      width="1400px"
      top="5vh"
    >
      <el-transfer
        v-model="chooseData"
        style="text-align: left; display: inline-block"
        filterable
        :titles="['待选-比对表清单', '已选-比对表清单']"
        :data="dataTableList"
      >
        <span slot-scope="{ option }">
          <el-tooltip
            class="item"
            :content="option.label"
            placement="top"
          >
            <span>{{ option.label }}</span>
          </el-tooltip>
        </span>
      </el-transfer>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="cancelChoose()">取消</el-button>
        <el-button type="primary" @click="submitChoose()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import tableTransferListApi from '@/api/data/table/tableTransferList'
import contrastListApi from '@/api/data/contrast/contrastList'
import contrastTemplateApi from '@/api/data/contrast/contrastTemplate'
import contrastTaskApi from '@/api/data/contrast/contrastTask'
import dataSourceApi from '@/api/metadata/dataSource'
import CRUD, { presenter, header, crud } from '@crud/crud'
import crudOperation from '@crud/expand/data/contrast/list/CRUD.operation.vue'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { downloadFile } from '@utils'
import { crunDate } from '@utils/data'
import { upload } from '@/api/data'

const defaultCrud = CRUD({
  title: '数据对比',
  url: '/api/cross/db/contrast/list',
  crudMethod: { ...contrastListApi }
})
export default {
  name: 'DataContrastList',
  // eslint-disable-next-line vue/no-unused-components
  components: { crudOperation, udOperation, pagination },
  mixins: [presenter(defaultCrud), header(), crud()],
  props: {
    form: {
      required: true,
      type: Object
    },
    taskPkId: {
      required: true,
      type: String
    },
    dialogType: {
      required: true,
      type: Number
    }
  },
  data() {
    return {
      contrastSceneOptions: [
        { key: 'TODAY', label: '当天' },
        { key: 'YESTERDAY', label: '昨天' },
        { key: 'ENDOFLASTMONTH', label: '上月末' },
        { key: 'FULL', label: '全表数据' }
      ],
      migrationTypeList: [],
      acceptFileType: '.xls,.xlsx',
      downloadLoading: false,
      loading: false,
      uploadLoading: false,
      fileList: [],
      filesList: [],
      whereCondition: '',
      sourceWhereCondition: '',
      targetWhereCondition: '',
      whereConditionIndex: '',
      whereConditionFlag: false,
      sortField: '',
      sourceSortField: '',
      targetSortField: '',
      sortFieldIndex: '',
      sortFieldFlag: false,
      customSql: '',
      sourceCustomSql: '',
      targetCustomSql: '',
      customSqlIndex: null,
      customSqlFlag: false,
      detailFlag: false,
      fieldFlag: false,
      fields: '',
      modelFlag: false,
      detailsFlag: false,
      tmpTableList: [],
      contrastTemplate: [],
      sourceConnList: [],
      targetConnList: [],
      dataDbList: [],
      dataTableList: [],
      tableName: [],
      tableId: [],
      createTaskType: '直连',
      chooseTable: false,
      chooseData: [],
      contrastSourceDbName: '',
      contrastTargetDbName: '',
      queryInfo: '',
      tableFieldsList: [],
      allRecords: []
    }
  },
  created() {
    this.initData()
    if (this.dialogType !== 1) {
      this.crud.notify('正在获取清单及其字段信息！', CRUD.NOTIFICATION_TYPE.SUCCESS)
    }
  },
  methods: {
    [CRUD.HOOK.beforeRefresh](crud) {
      if (this.taskPkId !== null && this.taskPkId !== '') {
        crud.query.taskPkId = this.taskPkId
      } else {
        crud.query.taskPkId = '123'
      }
    },
    [CRUD.HOOK.afterRefresh](crud) {
      this.form.dataContrastList = crud.data
    },
    // 初始化数据
    async initData() {
      this.initMigrationTypeList()
      this.getTemplate()
      this.crud.resetQuery(false)
      if (this.dialogType === 1) {
        this.form.taskName = `数据比对-${crunDate()}`
        const data = await dataSourceApi.findDefaultSource()
        const sourceDefault = data.find(item => item.isDefault === 'ENABLE' && item.sourceAttribute === 'source')
        const targetDefault = data.find(item => item.isDefault === 'ENABLE' && item.sourceAttribute === 'target')

        const migrationType = (sourceDefault === undefined ? '' : sourceDefault.sourceType) + '-' + (targetDefault === undefined ? '' : targetDefault.sourceType)
        if (this.migrationTypeList.some(item => item.name === migrationType && item.enabled === true)) {
          this.form.migrationType = migrationType
          this.changeMigrationType(this.form.migrationType)
          this.form.serverPkId = sourceDefault === undefined ? '' : sourceDefault.pkId
          this.form.targetConnPkId = targetDefault === undefined ? '' : targetDefault.pkId
        }
      } else {
        this.changeMigrationType(this.form.migrationType)
      }
      await this.getDatabaseByDataSource()
    },
    changeMigrationType(val) {
      if (val != null) {
        const sourceTypes = val.split('-')
        this.initSourceConnList(sourceTypes[0])
      } else {
        this.initSourceConnList()
      }
      // this.initTargetConnList(sourceTypes[1])
      this.form.database = ''
    },
    // 获取数据源信息
    initSourceConnList(sourceType) {
      const params = { serverType: 'SOURCE', status: 'ENABLE', sourceType: sourceType, size: 10000 }
      dataSourceApi.findListByPage(params).then(res => {
        if (res.total > 0) {
          this.sourceConnList = res.content
        }
      })
    },
    initTargetConnList(targetType) {
      const params = { serverType: 'TARGET', sourceType: targetType, size: 10000 }
      dataSourceApi.findListByPage(params).then(res => {
        if (res.total > 0) {
          this.targetConnList = res.content
        }
      })
    },
    initMigrationTypeList() {
      contrastTaskApi.getMigrationTypeInfos().then(res => {
        this.migrationTypeList = res
      })
    },
    // 获取模板信息
    getTemplate() {
      const param = { sourceAttribute: 'source', size: 500 }
      contrastTemplateApi.findListByPage(param).then(data => {
        this.contrastTemplate = data.content
      })
    },
    // 根据数据源信息获取数据库信息
    getDatabaseByDataSource() {
      this.form.sourceDbName = ''
      this.dataDbList = []
      if (this.form.serverPkId !== '') {
        dataSourceApi.schemas(this.form.serverPkId).then(data => {
          this.dataDbList = data
        })
      }
    },
    // where条件 修改提交
    whereConditionSubmit() {
      const sql = {
        sourceWhereCondition: this.sourceWhereCondition,
        targetWhereCondition: this.targetWhereCondition
      }
      this.form.dataContrastList[this.whereConditionIndex].whereCondition = JSON.stringify(sql)
      this.whereConditionFlag = false
    },
    // where条件 修改关闭
    whereConditionClose() {
      this.whereConditionFlag = false
    },
    // where条件 编辑
    whereConditionEdit(whereCondition, index) {
      this.whereCondition = ''
      this.sourceWhereCondition = ''
      this.targetWhereCondition = ''
      this.whereCondition = this.form.dataContrastList[index].whereCondition
      if (whereCondition !== undefined && whereCondition !== null && whereCondition !== '') {
        this.sourceWhereCondition = JSON.parse(this.whereCondition).sourceWhereCondition
        this.targetWhereCondition = JSON.parse(this.whereCondition).targetWhereCondition
      }
      this.whereConditionIndex = index
      this.whereConditionFlag = true
    },
    // 排序字段 修改提交
    sortFieldSubmit() {
      const sql = {
        sourceSortField: this.sourceSortField,
        targetSortField: this.targetSortField
      }
      this.form.dataContrastList[this.sortFieldIndex].sortField = JSON.stringify(sql)
      this.sortFieldFlag = false
    },
    // 排序字段 修改关闭
    sortFieldClose() {
      this.sortFieldFlag = false
    },
    // 排序字段 编辑
    sortFieldEdit(sortField, index) {
      this.sortField = ''
      this.sourceSortField = ''
      this.targetSortField = ''
      this.sortField = this.form.dataContrastList[index].sortField
      if (sortField !== undefined && sortField !== null && sortField !== '') {
        this.sourceSortField = JSON.parse(this.sortField).sourceSortField
        this.targetSortField = JSON.parse(this.sortField).targetSortField
      }
      this.sortFieldIndex = index
      this.sortFieldFlag = true
    },
    // 自定义SQL修改提交
    sqlSubmit() {
      const sql = {
        sourceCustomSql: this.sourceCustomSql,
        targetCustomSql: this.targetCustomSql
      }
      this.form.dataContrastList[this.customSqlIndex].customSql = JSON.stringify(sql)
      this.customSqlFlag = false
    },
    // 自定义SQL修改关闭
    sqlClose() {
      this.customSqlFlag = false
    },
    // 编辑自定义SQL
    customSqlEdit(customSql, index) {
      this.customSql = ''
      this.sourceCustomSql = ''
      this.targetCustomSql = ''
      this.customSql = this.form.dataContrastList[index].customSql
      if (customSql !== undefined && customSql !== null && customSql !== '') {
        this.sourceCustomSql = JSON.parse(this.customSql).sourceCustomSql
        this.targetCustomSql = JSON.parse(this.customSql).targetCustomSql
      }
      this.customSqlIndex = index
      this.customSqlFlag = true
    },
    // Excel导入相关
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    // Excel导入 移除操作
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleUploadJobChange(file, fileList) {
      if (this.form.contrastTemplatePkId === undefined || this.form.contrastTemplatePkId === '' || this.form.contrastTemplatePkId === null) {
        this.crud.notify('请先选择模板！', CRUD.NOTIFICATION_TYPE.WARNING)
        return
      } else if (this.form.serverPkId === undefined || this.form.serverPkId === '' || this.form.serverPkId === null) {
        this.crud.notify('请先选择源数据源类型！', CRUD.NOTIFICATION_TYPE.WARNING)
        return
      }
      const fileName = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (fileName !== 'xlsx' && fileName !== 'xls') {
        this.crud.notify('文件类型应为excel文件!', CRUD.NOTIFICATION_TYPE.ERROR)
        this.fileList = []
        return false
      }
      this.fileList = fileList
      if (this.fileList.length > 0) {
        this.uploadLoading = true
        const formData = new FormData()
        this.fileList.forEach((element, i) => {
          formData.append('file', element.raw)
        })
        formData.append('contrastTask', JSON.stringify(this.form))
        this.crud.notify('数据比对任务解析中...', CRUD.NOTIFICATION_TYPE.WARNING)
        upload('api/cross/db/contrast/list/importContrastList', formData).then(res => {
          this.uploadLoading = false
          this.taskPkId = res.taskId
          this.form.pkId = res.taskId
          if (res.status) {
            this.crud.notify('导入成功!', CRUD.NOTIFICATION_TYPE.SUCCESS)
            this.$refs.uploadExcel.clearFiles()
            this.crud.refresh()
          } else {
            this.taskPkId = '123'
            this.form.pkId = '123'
            this.crud.notify('导入失败!', CRUD.NOTIFICATION_TYPE.ERROR)
          }
        })
      } else {
        this.$notify.error({
          title: '错误',
          message: '请选择导入的文件!'
        })
      }
    },
    templateDownload() {
      const pkIds = this.crud.selections.map(item => {
        return item.pkId
      })
      this.downloadLoading = true
      contrastListApi.download(pkIds)
        .then(result => {
          downloadFile(result, '比对清单模板', 'xlsx')
          this.downloadLoading = false
        }).catch(() => {
          this.downloadLoading = false
        })
    },
    // 添加跨库比对任务与清单
    toAddTaskList() {
      if (this.form.contrastTemplatePkId === '') {
        this.crud.notify('请选择比对模板!', CRUD.NOTIFICATION_TYPE.WARNING)
        return
      }
      this.toAddTask()
      const param = {
        size: 100000,
        status: 'SUCCESS',
        sourceConnPkId: this.form.serverPkId,
        sourceDbName: this.form.sourceDbName
      }
      tableTransferListApi.findLatestSuccess(param).then(data => {
        this.dataTableList = []
        if (data.total > 0) {
          this.tmpTableList = data.content
          data.content.forEach(item => {
            const sourceTableName = item.sourceDbName + '.' + item.sourceTableName
            const targetTableName = item.targetDbName + '.' + item.targetTableName
            const label = sourceTableName + ' -> ' + targetTableName + ' [' + item.sourceConnName + '-' + item.targetConnName + ']'
            this.dataTableList.push({ key: item.pkId, label: label })
          })
        }
        this.initSelectTableList()
      }).catch(err => {
        console.log(err)
      })
    },
    initSelectTableList() {
      const param = {
        taskPkId: this.taskPkId
      }
      tableTransferListApi.findAllRecords(param).then(data => {
        this.allRecords = data.content
        this.chooseData = []
        this.dataTableList.forEach(item => {
          this.allRecords.forEach(item2 => {
            if (item.key === item2.tableTransferPkId) {
              this.chooseData.push(item.key)
            }
          })
        })
        this.chooseTable = true
      })
    },
    // 添加跨库比对任务
    toAddTask() {
      if (this.form.pkId === null || this.form.pkId === '') {
        contrastTaskApi.add(this.form).then(rsp => {
          // this.taskPkId = rsp
          this.form.pkId = rsp
        })
      }
    },
    // 添加跨库比对清单
    toAddList() {
      const param = { pkId: this.form.serverPkId, schema: this.form.sourceDbName }
      dataSourceApi.tables(param).then(data => {
        data.forEach((array) => {
          this.dataTableList.push({
            label: array,
            key: array
          })
        })
      })
      this.chooseTable = true
    },
    // 退出穿梭框选择表界面
    cancelChoose() {
      this.chooseTable = false
      this.dataTableList = []
      this.chooseData = []
    },
    // 提交穿梭框选择的表
    submitChoose() {
      this.chooseTable = false
      this.addContrastList()
    },
    // 穿梭框选择的表形成对比清单
    addContrastList() {
      const newChooseData = this.dealChooseData(this.chooseData)
      this.crud.notify('正在获取字段信息', CRUD.NOTIFICATION_TYPE.SUCCESS)
      newChooseData.forEach(async(transferListPkId) => {
        const info = { pkId: transferListPkId }
        const data = await tableTransferListApi.findListByPage(info)
        const param = {
          taskPkId: this.taskPkId,
          sourceDbName: this.form.sourceDbName,
          sourceTableName: data.content[0].sourceTableName,
          contrastDbName: data.content[0].targetDbName,
          contrastTableName: data.content[0].targetTableName,
          serverPkId: this.form.serverPkId,
          contrastServerPkId: data.content[0].targetConnPkId,
          tableTransferPkId: data.content[0].pkId
        }
        await contrastListApi.add(param)
        await this.crud.refresh()
      })
    },
    dealChooseData(chooseList) {
      const tmpList = []
      this.form.dataContrastList.forEach(info => {
        tmpList.push(info.tableTransferPkId)
      })
      chooseList = chooseList.filter(function(item) {
        return tmpList.indexOf(item) < 0
      })
      return chooseList
    },
    // 动态禁用选择要迁移的表按钮
    chooseTableDisable() {
      return this.dialogType === 0 || this.form.taskName === null || this.form.taskName === '' ||
        this.form.contrastTemplatePkIds === [] || this.form.serverPkId === '' || this.form.sourceDbName === ''
    },
    async toDelete(datas) {
      await this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.delAllLoading = true
        this.crud.doDelete(datas)
      }).catch(() => {
      })
      // 目的是删除之后刷新一下 this.form.dataContrastList
      const param = { taskPkId: this.form.pkId }
      await contrastListApi.findListByPage(param).then(data => {
        this.form.dataContrastList = data.content
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.el-divider--horizontal {
  margin: 5px 0px;
};
::v-deep .el-transfer-panel{
  width: 580px;
  height: 500px;
}
::v-deep .el-transfer-panel__list{
  height: 400px;
}
</style>
